
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.algorithm.transformer {
import org.goverla.collections.ArrayList;
import org.goverla.collections.HashMap;
import org.goverla.collections.ListCollectionViewIterator;
import org.waveprotocol.wave.model.document.operation.AnnotationBoundaryMap;
import org.waveprotocol.wave.model.document.operation.algorithm.ValueUpdate;

/**
 *Abstract Annotation Tracker
 **/
public class AnnotationTracker {

	var active:HashMap= new HashMap();
	private var maps:ArrayList= new ArrayList();
	private var processor:AnnotationProcessor;

	function AnnotationTracker( processor:AnnotationProcessor) {
		this.processor = processor;
	}

	final function buffer(map:AnnotationBoundaryMap):void {
		maps.addItem(map);
	}

	public final function flush():void {
		processAll();
	}

	final function sync():void {
		processor.sync();
	}

	final function startDeletion():void {
		opposingTracker().processAll();
		processor.cursor.annotationBoundary(opposingTracker().processor
				.toSynced(processor.active));
	}

	final function endDeletion():void {
		processor.cursor.annotationBoundary(opposingTracker().processor
				.fromSynced(processor.active));
	}

	final function processAll():void {
		var itr:ListCollectionViewIterator = new ListCollectionViewIterator(maps);
		while(itr.hasNext()) {
			process(AnnotationBoundaryMap(itr.next()));
		}
		maps.removeAll();
	}

	private final function process(map:AnnotationBoundaryMap):void {
		for (var i:int= 0; i < map.endSize(); ++i) {
			active.removeItemAt(map.getEndKey(i));
		}
		for (var i:int= 0; i < map.changeSize(); ++i) {
			active.addItem(map.getChangeKey(i), new ValueUpdate(map.getOldValue(i),
					map.getNewValue(i)));
		}
		processUpdate(map);
	}

	function processUpdate(map:AnnotationBoundaryMap):void {};

	function opposingTracker():AnnotationTracker {return null;};

}
}